import styles from './index.module.scss'
import Dialog from '@c/dialog'
import Button from '@c/button'
import { useEffect, useState, useRef } from 'react'
import cm from 'classnames'
import { convertScore } from '@/api/score'
import message from '@c/message'

const Index = props => {
  const { onClose, data } = props
  const ref = useRef()
  const [contentClass, setContentClass] = useState(styles.smallBg)

  useEffect(() => {
    const resizeClass = () => {
      const height = ref.current ? ref.current.offsetHeight : 400
      if (400 <= height && height <= 500) {
        setContentClass(styles.smallContent)
      } else if (500 < height && height <= 600) {
        setContentClass(styles.middleContent)
      } else {
        setContentClass(styles.largeContent)
      }
    }
    resizeClass()
    window.addEventListener('resize', resizeClass)
    return () => {
      window.removeEventListener('resize', resizeClass)
    }
  }, [])
  const toScore = () => {
    onClose?.()
    window.location.href = '/points?to=convert'
  }

  const toConvert = async () => {
    const res = await convertScore({ exchangeId: data.exchangeId })
    if (res.code === 0) {
      message({ content: '积分兑换成功' })
      onClose()
    } else {
      message({ content: res.msg })
    }
  }

  return (
    <Dialog className={cm(styles.content, contentClass)}>
      <div className={styles.bg} ref={ref}>
        <img className={styles.bgImg} src="/images/s1.webp" alt="" />
        <p className={styles.getScore}>恭喜！获得{data.activePoint}积分</p>
        <p className={styles.getTips}>
          使用{data.exchangePoint}积分兑换<span>{data.date}VIP会员</span>权益
        </p>
        <Button className={styles.convert} onClick={toConvert}>
          立即兑换
        </Button>
      </div>
      <img src="/images/s2.webp" className={styles.light} alt="光束背景" />
      <p className={styles.mores} onClick={toScore}>
        获取更多会员
      </p>
      <img src="/images/close-score.webp" alt="" className={styles.closeModal} onClick={onClose} />
    </Dialog>
  )
}

export default Index
